if(@ARGV == 0)
{
	die "no arguments\n";
}
for($i=0;$i<@ARGV-1;$i++)
{
	$file = $ARGV[$i];
	chomp($file);
	$tfam = "TFAM$i";
	open $tfam,"<$file.tfam" or die "can't open the file $file.tfam\n";
	#$tped = "TPED$i";
	#open $tped,"<$file.tped" or die "can't open the file $file.tped\n";
	$file[$i] = $file;
	#if($i != 0)
	#{
	#	$sys = "perl /data4/bsi/RandD/Workflow/tcga_genotyping/scripts/perl_flip_strand.pl $file[0].tped $file.tped $file"."_new.tped";
	#	print "$sys\n";
	#	system($sys);
	#	$sys = "mv $file"."_new.tped "."$file.tped";
	#	print "$sys\n";
	#	#system($sys);
	#}	
}
@file_flip = @file;
$length = @file_flip;
for($i=0;$i<$length;$i++)
{
	$intial = shift(@file_flip);
	for($y=0;$y<@file_flip;$y++)
	{
		$sys = "perl /data2/bsi/RandD/Arraybased_RND/tcga_genotyping/scripts/perl_flip_strand.pl $intial.tped $file_flip[$y].tped $file_flip[$y]"."_new.tped";
		print "$sys\n";
		system($sys);
		$sys = "mv $file_flip[$y]"."_new.tped $file_flip[$y].tped";
		print "$sys\n";
		system($sys);
	}
}
print "@file\n";
$wrfile = $ARGV[@ARGV-1];
chomp($wrfile);
$wrfile_temp = $wrfile."_temp";
open(WRTFAM,">$wrfile_temp.tfam");
open(MERGE,">$wrfile.merge");
for($i=0;$i<@ARGV-1;$i++)
{
	$tfam = "TFAM$i";
	$ntfam = "NTFAM$i";
	$file1[$i] = $file[$i]."_fake";
	$file2[$i] = $file[$i]."_temp";
	print "$file[$i] $file1[$i] $file2[$i]\n";
	open($ntfam,">$file1[$i].tfam");
	while($line = <$tfam>)
	{
		print WRTFAM $line;
		$round = sprintf("%.0f", rand()*time());
		print $ntfam "$round $round 0 0 -9 -9\n";
	}
	$sys = "mv $file[$i].tfam $file2[$i].tfam";
	print $sys."\n";
        system($sys);
	$sys = "mv $file1[$i].tfam $file[$i].tfam";	
	print $sys."\n";
        system($sys);
	$sys = "/data4/bsi/RandD/Workflow/genotyping_QC_FWD/bin/plink/plink --tfile $file[$i] --make-bed --out $file[$i]";
	print $sys."\n";
	system($sys);
	if (!(-e "$file[$i].fam")) {
        die "input fam file $file[$i].fam does not exist\n";
}
	
	system("rm $file[$i].log");
	system("rm $file[$i].nosex");
	system("rm $file[$i].nof");
	system("rm $file[$i].hh");
	system("mv $file2[$i].tfam $file[$i].tfam");
	if($i != 0)
	{
		print MERGE "$file[$i].bed $file[$i].bim $file[$i].fam\n";
	}
}
$sys = "/data4/bsi/RandD/Workflow/genotyping_QC_FWD/bin/plink/plink --bfile $file[0] --merge-list $wrfile.merge --recode --transpose --out $wrfile";
print $sys."\n";
system($sys);
system("mv $wrfile_temp.tfam $wrfile.tfam");
